from rest_framework.serializers import ModelSerializer
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings
import re
from django_redis import get_redis_connection

from goods.models import SKU
from .models import User, Address
from celery_tasks.email.tasks import send_verify_email


class CreateUserSerializer(ModelSerializer):
    """注册序列化器"""
    password2 = serializers.CharField(label='确认密码', write_only=True)
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    allow = serializers.CharField(label='同意协议', write_only=True)
    token = serializers.CharField(label='登陆状态token', read_only=True)  # 增加token字段

    class Meta:
        model = User
        # 模型中没有的字段(不需要保存): password, allow, sms_code
        fields = ['id', 'username', 'mobile', 'password', 'password2', 'sms_code', 'allow', 'token']
        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    def validate_mobile(self, value):
        """校验手机号"""
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError("手机号格式错误")
        return value

    def validate_allow(self, value):
        """校验用户是否同意协议"""
        if value != 'true':
            raise serializers.ValidationError('请同意用户协议')
        return value

    def validate(self, data):
        # 判断两次密码
        if data['password'] != data['password2']:
            raise serializers.ValidationError('两次密码不一致')

        # 判断短信验证码
        redis_conn = get_redis_connection('verify_code')
        mobile = data['mobile']
        real_sms_code = redis_conn.get('sms_%s' % mobile)
        if not real_sms_code:
            raise serializers.ValidationError('无效的短信验证码')
        if real_sms_code.decode() != data['sms_code']:
            raise serializers.ValidationError('短信验证码有误')

        return data

    def create(self, validated_data):
        # 重写序列化器的create方法,将password2,sms_code,allow从validated_data字典中移除
        validated_data.pop('password2')
        validated_data.pop('sms_code')
        validated_data.pop('allow')

        # user = User.objects.create(**validated_data)
        # user = super(CreateUserSerializer, self).create(validated_data)
        user = User(**validated_data)
        # 用django的认证系统对密码进行加密
        user.set_password(validated_data['password'])
        user.save()
        # 加载jwt配置中处理载荷payload的函数
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        # 加载生成token的函数
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        # 传入对象来生成payload
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token

        return user


class UserDetailSerializer(ModelSerializer):
    """用户个人信息序列化器"""
    class Meta:
        model = User
        fields = ['id', 'username', 'mobile', 'email', 'email_active']


class EmailViewSerializer(ModelSerializer):
    """邮箱设置序列化器"""
    class Meta:
        model = User
        fields = ['id', 'email']
        extra_kwargs = {
            'email': {
                'required': True
            }
        }

    # ModelSerializer中有updata方法,重写是为了后面发邮件
    def update(self, instance, validated_data):
        # 给user模型的email赋值
        instance.email = validated_data['email']
        instance.save()
        # 发送验证邮件
        verify_url = instance.generate_email_verify_url()
        send_verify_email.delay(instance.email, verify_url)
        return instance


class UserAddressSerializer(serializers.ModelSerializer):
    """用户地址序列化器"""
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    class Meta:
        model = Address
        exclude = ['user', 'is_deleted', 'create_time', 'update_time']

    def validate_mobile(self, value):
        """验证手机号"""
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def create(self, validated_data):
        """保存用户地址"""
        user = self.context['request'].user
        validated_data['user'] = user
        return Address.objects.create(**validated_data)


class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """
    class Meta:
        model = Address
        fields = ('title',)


class UserBrowseHistorySerializer(serializers.Serializer):
    """浏览历史记录序列化器"""
    # 创建字段
    sku_id = serializers.IntegerField(label='商品SKU编号', min_value=1)

    def validate_sku_id(self, value):
        """校验sku_id是否存在"""
        try:
            SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('该商品不存在')
        return value

    def create(self, validated_data):
        """重写保存方法"""
        # 获取sku_id
        sku_id = validated_data['sku_id']
        # 获取当前登陆用户
        user_id = self.context['request'].user.id
        # 创建redis连接对象
        redis_conn = get_redis_connection('history')
        # 创建管道
        pl = redis_conn.pipeline()
        # 去重
        pl.lrem('history_%s' % user_id, 0, sku_id)
        # 将sku_id添加到列表中
        pl.lpush('history_%s' % user_id, sku_id)
        # 只保存最多5条记录
        pl.ltrim('history_%s' % user_id, 0, 4)
        # 执行
        pl.execute()

        return validated_data

